#!/usr/bin/python2.7
#coding=utf8

import sys

def parsing():
    #读取CSV文件,一行一行解析
    csvfilepath=getcsvfilepath()
    #print(csvfilepath)
    obj=open(csvfilepath,"r")
    databasename=getDataBasename()
    if databasename == "oracle":
        parse_oracle(obj)
    elif databasename == "sqlalchemy_oracle":
        parse_sqlalchemy_oracle(obj)
    else :
        print("Error No such databasename ")
        sys.exit(1)
    
    
    
    
    
        
    
    
    
    
    
def getDataBasename():
    from conf.globalconfiguration import Config
    return Config().DATABASENAME
    
    
def getcsvfilepath():
    from conf.globalconfiguration import Config
    return Config().CSVFILEPATH
    
    
    
def parse_oracle(obj):
    from conf.globalconfiguration import Config
    sqlfilepath=Config.ORACLESQLFILEPATH
    sqlfile=open(sqlfilepath,"w")
    tablename=""
    #print(sqlfile)
    for line in obj:
        #print(type(line))
        line=line.encode("utf8")
        #print(type(line))
        #print(line)
        fields=line.split(",".encode("utf8"))
        if fields[0] == "tablename".encode('utf8'):
            tablename=fields[1]
            aa="create table ".encode('utf8')+tablename+" (\n".encode('utf8')
            sqlfile.write(aa.decode("gb2312"))
        elif fields[0] == "column".encode('utf8'):
            #判断数据库
            print("uiretllllllllglllllllguilqrte")
            if getDataBasename() == "oracle":
                from database.oracle.conf import Dataformat
                dataformat=Dataformat()
                print("defrewgftregtrgh")
                if fields[4] == "是".encode('utf8'):
                    #print("是")
                    aa=fields[1]+" ".encode('utf8')+dataformat.transfer(fields[3])+",\n".encode('utf8')
                    sqlfile.write(aa.decode("gb2312"))
                else :
                    #print("否")
                    aa=fields[1]+" ".encode('utf8')+dataformat.transfer(fields[3])+" not null,\n".encode('utf8')
                    sqlfile.write(aa.decode("gb2312"))
        elif fields[0] == "primarykey".encode('utf8'):
            aa="constraint pk_%s primary key (%s) ,\n".encode('utf8') % (tablename,fields[1])
            sqlfile.write(aa.decode("gb2312"))
        elif fields[0] == "restrict".encode('utf8'):
            #print(fields[1])
            restrict_keys=fields[1]
            #print(restrict_keys)
            src=u'、'.encode("utf8")
            #print restrict_keys.find(src)
            restrict_keys=restrict_keys.replace(src,",".encode('utf8'))
            aa="constraint %s_unique unique(%s) \n".encode('utf8') % (tablename,restrict_keys)
            sqlfile.write(aa.decode("gb2312"))
        elif fields[0] == "end".encode('utf8'):
            aa=");\n".encode('utf8')
            sqlfile.write(aa.decode("gb2312"))
        elif fields[0] == "stop".encode('utf8'):
            break
        else :
            print(fields[0])
            print("ERROR! csvfile format had error")
            sys.exit(1)
    obj.close()
    
def parse_sqlalchemy_oracle(obj):
    from conf.globalconfiguration import Config
    from database.sqlalchemy_oracle.conf import Dataformat
    dataformat=Dataformat()
    sqlfilepath=Config.SQLALCHEMY_ORACLESQLFILEPATH
    sqlfile=open(sqlfilepath,"w")
    sqlfile.write(dataformat.cx_oracle_head)
    tablename=""
    #print(sqlfilepath)
    for line in obj:
        line=line.decode(Config.CSVFILECODING).encode("utf8")
        fields=line.split(",")
        if fields[0] == "tablename":
            tablename=fields[1]
            sqlfile.write("class %s (Base):\n" % tablename.title())
            sqlfile.write('    __tablename__="%s" \n' % (tablename.upper()))
        elif fields[0] == "column":
            if fields[1] == "id":
                sqlfile.write('    %s = Column(%s, Sequence("seq_%s_id"),primary_key=True)\n' % (fields[1],dataformat.transfer(fields[3]),tablename.lower()))
            elif (fields[1] == "create_time") or (fields[1] =="update_time"):
                if fields[4] == u"是".encode('utf8'):
                    sqlfile.write("    %s = Column(%s, nullable=%s ,default=datetime.datetime.now())\n" % (fields[1],dataformat.transfer(fields[3]),"True"))
                else :
                    sqlfile.write("    %s = Column(%s, nullable=%s ,default=datetime.datetime.now())\n" % (fields[1],dataformat.transfer(fields[3]),"False"))
            else :
                if fields[4] == u"是".encode('utf8'):
                    sqlfile.write("    %s = Column(%s, nullable=%s)\n" % (fields[1],dataformat.transfer(fields[3]),"True"))
                else :
                    sqlfile.write("    %s = Column(%s, nullable=%s)\n" % (fields[1],dataformat.transfer(fields[3]),"False"))
        elif fields[0] == "primarykey":
            pass
            #sqlfile.write("    constraint pk_%s primary key (%s) ,\n" % (tablename,fields[1]))
        elif fields[0] == "restrict":
            restrict_keys=fields[1]
            src=u'、'.encode("utf8")
            restrict_keys=restrict_keys.replace(src,",")
            restrict_keys=restrict_keys.split(",")
            res=[]
            for i in range(len(restrict_keys)):
                res.append(tablename.title()+"."+restrict_keys[i])
            res_str=",".join(res)
            sqlfile.write("Index('data_%s_unique', %s, unique=True)\n" % (tablename,res_str))
        elif fields[0] == "end":
            sqlfile.write("\n\n\n")
        elif fields[0] == "stop":
            break
        else :
            print("ERROR! csvfile format had error")
            sys.exit(1)
    obj.close()